/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package fr.loof.fonzie;

import java.util.Iterator;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 * @author <a href="nicolas@apache.org">Nicolas De Loof</a>
 */
public class DefaultQueryExecutor
    implements QueryExecutor
{

    @PersistenceContext
    EntityManager entityManager;

    /**
     * @param entityManager
     */
    public DefaultQueryExecutor( EntityManager entityManager )
    {
        super();
        this.entityManager = entityManager;
    }

    /**
     * {@inheritDoc}
     *
     * @see fr.loof.fonzie.QueryExecutor#execute(PersistenceQuery, Object[], boolean)
     */
    public Object execute( PersistenceQuery query, Object[] args, boolean singleResult )
    {
        Query q = query.createQuery( entityManager );
        int position = 0;
        Iterator<String> parameters = query.parameters();
        while ( parameters.hasNext() )
        {
            q.setParameter( parameters.next(), args[position++] );
        }

        if ( args.length > position )
        {
            q.setMaxResults( (Integer) args[position++] );
        }
        if ( args.length > position )
        {
            q.setFirstResult( (Integer) args[position] );
        }
        return singleResult ? q.getSingleResult() : q.getResultList();
    }

}
